<script lang="ts" setup>
import { getCurrentInstance, ref, inject } from 'vue'
import { onLoad, onPageScroll, onReady, onShow } from '@dcloudio/uni-app'
import TnLineProgress from '@tuniao/tnui-vue3-uniapp/components/line-progress/src/line-progress.vue'
import TnPicker from '@tuniao/tnui-vue3-uniapp/components/picker/src/picker.vue'
import { addPlanApi, delPlansApi, updatePlanApi } from '@/services/api'

const openPicker = ref(false)
const planDetail = ref()
const wordAll = ref() //每天单词数
const needDay = ref() //需要天数
const morningLearnSum = ref() //早上听的数量
const nightLearnSum = ref() //晚上听的数量
const wordNumber = ref([10, 20, 30, 40, 50])
const pickerValue = ref([] as any)
const needDate = ref()
const dayNumber = ref([] as any)
const ifFinish = ref(0)
//剩余单词数
const onPickerChange = (e) => {
  if (e.detail.value[0] != pickerValue.value[0]) {
    console.log('左边')
    pickerValue.value = [e.detail.value[0], e.detail.value[0]]
    wordAll.value = wordNumber.value[e.detail.value[0]]
    setDate()
    return
  }
  if (e.detail.value[1] != pickerValue.value[1]) {
    console.log('右边')
    pickerValue.value = [e.detail.value[1], e.detail.value[1]]
    wordAll.value = wordNumber.value[e.detail.value[1]]
    setDate()
    return
  }
}
onLoad((options) => {
  console.log(planDetail.value, '7878787878787878787878')
  // removeLeadingZerosFromTime('08:00')
  if (options.ifFinish == 1) {
    ifFinish.value = 1
  }
  planDetail.value = options.data
    ? JSON.parse(decodeURIComponent(options.data))
    : null
  console.log(planDetail.value)
  wordNumber.value.forEach((item) => {
    dayNumber.value.push(
      Math.ceil(
        (planDetail.value.lessonSum - planDetail.value.hadLearnSum) / item
      )
    )
  })
  console.log(dayNumber.value, 'dayNumber.value')
  console.log(planDetail.value)
  // 如果存在计划planId，则显示计划详情
  if (planDetail.value.planId) {
    //早上跟晚上的单词数量
    // morningLearnSum.value = planDetail.value.morningStudyInfo.morningLearnSum
    // nightLearnSum.value = planDetail.value.nightStudyInfo.nightLearnSum
    // const index1 = wordNumber.value.indexOf(morningLearnSum.value)
    // const index2 = wordNumber.value.indexOf(nightLearnSum.value)

    // pickerValue.value = [index1, index2]
    //计算每日读几个单词
    // wordAll.value = morningLearnSum.value + nightLearnSum.value
    wordAll.value = planDetail.value.planPerDayNum
    setDate()
    setTimeout(() => {
      pickerValue.value = [
        wordNumber.value.indexOf(wordAll.value),
        wordNumber.value.indexOf(wordAll.value),
      ]
    }, 0)
  } else {
    setTimeout(() => {
      pickerValue.value = [0, 0]
      wordAll.value = wordNumber.value[0]
    }, 0)
  }
})
const toMyInterview = async () => {
  if (!checking()) {
    return false
  }
  const params = {
    bookId: planDetail.value.bookId,
    learnType: planDetail.value.learnType,
    perDayNum: wordAll.value,
    scenseType: planDetail.value.scenseType,
  }
  //已经完成需要重新制定计划
  if (ifFinish.value == 1) {
    //清空计划之后新增计划
    const data = await delPlans()
    if (data) {
      //新增
      const data = await addPlanApi(params)
      if (data.code === 200) {
        uni.showToast({
          title: '重新制定计划成功',
          icon: 'none',
        })
        uni.navigateBack({
          delta: 1,
        })
      }
    }
  } else {
    if (planDetail.value.planId) {
      params.planId = planDetail.value.planId
      console.log(params)
      console.log('更新')
      //更新
      const data = await updatePlanApi(params)
      if (data.code === 200) {
        uni.showToast({
          title: '更新成功',
          icon: 'none',
        })
        uni.navigateBack({
          delta: 1,
        })
      }
    } else {
      console.log('新增')
      console.log(params)
      //新增
      const data = await addPlanApi(params)
      if (data.code === 200) {
        uni.showToast({
          title: '计划添加成功',
          icon: 'none',
        })
        uni.navigateBack({
          delta: 1,
        })
      }
    }
  }

  console.log('params', params)
}
//清空计划之后新增计划
const delPlans = async () => {
  const data = await delPlansApi({
    planIds: [planDetail.value.planId],
  })
  if (data.code === 200) {
    console.log('清楚计划成功，请制定计划')
    return true
  }
}
//校验不为空
const checking = () => {
  if (!wordAll.value) {
    uni.showToast({
      title: `请选择每天${
        planDetail.value.learnType == 1
          ? '单词'
          : planDetail.value.learnType == 2
            ? '句子'
            : planDetail.value.learnType == 3
              ? '课文'
              : ''
      }数`,
      icon: 'none',
    })
    return false
  }
  return true
}
// onLoad(() => {
//   wordNumber.value.forEach((item) => {
//     dayNumber.value.push(Math.ceil(wordNumberValue.value / item))
//   })
//   console.log(dayNumber.value)
//   setTimeout(() => {
//     pickerValue.value = [3, 3]
//     setDate()
//   }, 100)
//   console.log(formatTimestampToDate(needDate.value.getTime()))
// })
//将时间戳转为日期的函数
const formatTimestampToDate = (timestamp) => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}
const setDate = () => {
  //计算需要的天数
  needDay.value = Math.ceil(
    (planDetail.value.lessonSum - planDetail.value.hadLearnSum) / wordAll.value
  )
  console.log(needDay.value, 'iii')
  //当前日期加上完成天数的时间戳
  needDate.value = formatTimestampToDate(
    new Date().getTime() + needDay.value * 86400000
  )
}
const openPicker1 = ref(false)
const pickerValue1 = ref(['数值1', '数值2-a', '数值4-b'])

const pickerData1 = [
  ['数值1', '数值2', '数值3', '数值4', '数值5'],
  ['数值1-a', '数值2-a', '数值3-a', '数值4-a', '数值5-a'],
  ['数值1-b', '数值2-b', '数值3-b', '数值4-b', '数值5-b'],
]
</script>

<template>
  <view class="contain">
    <view class="main_box_list">
      <view class="bookStyleBox">
        <view class="bookImg">
          <image :src="planDetail.bookUrl" />
        </view>
        <view class="right_box">
          <view class="title_Line">
            <view class="title"> 自然拼读全能大课堂 </view>
          </view>
          <view class="right_text">
            每日{{ wordAll ? wordAll : '/' }}个，剩余{{
              needDay ? needDay : '/'
            }}天
          </view>

          <view class="progress">
            <TnLineProgress
              :percent="
                planDetail.hadLearnSum == 0
                  ? 0
                  : (planDetail.hadLearnSum / planDetail.lessonSum) * 100
              "
              active-color="#3388FF"
              height="10"
            />
          </view>
          <view class="text_number">
            {{ planDetail.hadLearnSum }}/{{ planDetail.lessonSum }}
          </view>
        </view>
      </view>
    </view>
    <view class="setting">
      <view class="title">
        预计完成日期：
        <text>{{ needDate }}</text>
      </view>
      <view class="setting_box">
        <view class="title_box">
          <view class="text">
            每天学{{
              planDetail.learnType == 1
                ? '单词'
                : planDetail.learnType == 2
                  ? '句子'
                  : planDetail.learnType == 3
                    ? '课文'
                    : ''
            }}
          </view>
          <view class="text"> 完成天数 </view>
        </view>

        <view class="set_box">
          <picker-view
            :value="pickerValue"
            class="picker-view"
            indicator-class="picker-view-column"
            @change="onPickerChange"
          >
            <picker-view-column>
              <view
                class="item"
                v-for="(item, index) in wordNumber"
                :key="index"
                >{{ item }}个</view
              >
            </picker-view-column>
            <picker-view-column>
              <view class="item" v-for="(item, index) in dayNumber" :key="index"
                >{{ item }}天</view
              >
            </picker-view-column>
          </picker-view>
        </view>
      </view>
      <!-- <TnPicker
        v-model="pickerValue1"
        v-model:open="openPicker1"
        :data="pickerData1"
      >
        <template #cancel>再考虑一下</template>
        <template #confirm>主意已决</template>
      </TnPicker> -->
    </view>

    <view class="btn">
      <TnButton
        bg-color="#5155E6"
        text-color="#fff"
        width="100%"
        height="80rpx"
        font-size="36rpx"
        @tap="toMyInterview"
        >保存计划</TnButton
      >
    </view>
  </view>
</template>

<style lang="scss" scoped>
.contain {
  width: 100%;
  padding: 20rpx 32rpx;
  .main_box_list {
    width: 100%;
    background: #fff;
    border-radius: 20rpx;
    padding: 32rpx 32rpx 0;
    margin-top: 32rpx;
    margin-bottom: 32rpx;
    .bookStyleBox {
      width: 100%;
      display: flex;
      padding-bottom: 32rpx;
      .bookImg {
        width: 120rpx;
        height: 180rpx;
        object-fit: contain;
        margin-right: 20rpx;
      }
      .right_box {
        flex: 1;
        .title_Line {
          width: 100%;
          display: flex;
          justify-content: space-between;
          .title {
            font-size: 36rpx;
            color: #101010;
          }
        }
        .right_text {
          font-size: 26rpx;
          color: #000000;
          font-weight: bold;
          margin: 8rpx 0;
        }
        .progress {
          margin: 16rpx 0;
        }
        .text_number {
          color: #6c6c6c;
          font-size: 28rpx;
        }
      }
    }
  }
  .setting {
    width: 100%;
    .title {
      font-size: 24rpx;
      color: #101010;
      font-weight: bold;
      text {
        color: #0f40f5;
      }
    }
    .setting_box {
      width: 100%;
      background: #fff;
      margin-top: 30rpx;
      border-radius: 20rpx;
      .title_box {
        border-bottom: 2rpx solid #e8e8e8;
        display: flex;
        justify-content: space-between;
        height: 90rpx;
        .text {
          width: 50%;
          text-align: center;
          line-height: 90rpx;
          font-size: 32rpx;
          font-weight: bold;
        }
      }
      .set_box {
        padding: 0 10rpx;
        .picker-view {
          width: 100%;
          height: 300rpx;
          margin-top: 20rpx;
        }
        .item {
          line-height: 68rpx;
          text-align: center;
        }
        :deep(.picker-view-column) {
          background: #3388ff;
          opacity: 0.3;
          color: #000000;
          font-weight: bold;
          font-size: 40rpx;
          border-radius: 10rpx;
        }
      }
    }
  }
  .btn {
    padding: 0 32rpx;
    width: 100%;
    position: fixed;
    bottom: 10rpx;
    left: 0;
  }
}
</style>
